package com.homework.action;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.homework.service.UserService;
import com.homework.util.Constants;
import com.opensymphony.xwork2.ActionContext;

public class ChangePasswordAction {
	private UserService userService = new UserService();

	private String oldPassword;
	private String newPassword;

	public String getOldPassword() {
		return oldPassword;
	}

	public void setOldPassword(String oldPassword) {
		this.oldPassword = oldPassword;
	}

	public String getNewPassword() {
		return newPassword;
	}

	public void setNewPassword(String newPassword) {
		this.newPassword = newPassword;
	}

	public String execute() {

		if (getNewPassword().isEmpty()) {
			return "Error";
		}
		if (getOldPassword().isEmpty()) {
			return "Error";
		}

		HttpServletRequest request = ServletActionContext.getRequest();
		Object userId = -1;
		if (ActionContext.getContext().getSession().get("userId") == null) {
			// 返回用户未登录
			request.setAttribute("message",Constants.MESSAGE_ERROR_UserNeedLogin);
			return "Error";
		} else {
			//从session中获取用户id
			userId = ActionContext.getContext().getSession().get("userId");
		}
		
		if (!userService.passwordCheck(userId, getOldPassword())) {
			// 返回旧密码错误提示
			request.setAttribute("message",Constants.MESSAGE_ERROR_OldPasswordError);
			return "pwdError";
		}
		if (userService.changePassword(userId, getNewPassword())) {
			//密码修改成功
			request.setAttribute("message",Constants.MESSAGE_SUCCESS_ChangePasswordSuccess);
			return "success";
		}
		// 系统错误
		return "Error";
	}
}
